<template>
    <div class="draggable-navbar"
        :style="{
            position: 'absolute',
            userSelect: isDragging ? 'none' : 'auto',
            cursor: 'default',
            top:`${props.y}px`,
            left:`${props.x}px`,
        }" 
        @mousedown="onMouseDown">
        <slot></slot>
    </div>
</template>
  
<script setup lang="ts">
//申明坐标修改事件
const $emit = defineEmits(['startMove','onMoving','endMove']);
const props = defineProps({
    index : {
        type: Number,
        default: 0
    },
    x: {
            type: Number,
            default: 0
        },
    y: {
        type: Number,
        default: 0
        },
    axis:{
        type: String,
        default: 'both'
    }
})
// console.log('测试传值',props.x,props.y)
const isDragging = ref(false);
const MouseStartPosition = reactive({ x: 0, y: 0 });
const WinStartPosition = reactive({ x: 0, y: 0 });
const currentX = ref(props.x);
const currentY = ref(props.y);

function onMouseDown(event:any) {
    // event.preventDefault();    
    if(event.button === 0 ){ //鼠标左键触发拖拽
      isDragging.value = true;
      MouseStartPosition.x = event.clientX;
      MouseStartPosition.y = event.clientY;
      const rect = event.currentTarget.getBoundingClientRect();
      WinStartPosition.x = rect.left + window.scrollX;
      WinStartPosition.y = rect.top + window.scrollY;    
      $emit('startMove',props.index,WinStartPosition);      
      window.addEventListener('mousemove', onMouseMove);
      window.addEventListener('mouseup', onMouseUp);
    }
  }

  function onMouseUp() {
    // event.preventDefault();
    $emit('endMove',props.index);
    isDragging.value = false;
    window.removeEventListener('mousemove', onMouseMove);
    window.removeEventListener('mouseup', onMouseUp);
    // console.log('拖拽结束')
  }

  function onMouseMove(event:any) {
    // event.preventDefault();
    // console.log('拖拽中....',WinStartPosition)
    if (isDragging.value) {
      if (props.axis==="x"|| props.axis==="both"){
        currentX.value = event.clientX - MouseStartPosition.x + WinStartPosition.x;
      }
      if (props.axis==="y"|| props.axis==="both"){
        currentY.value = event.clientY - MouseStartPosition.y + WinStartPosition.y;
      }
      $emit('onMoving',props.index,currentX.value);
    }    
  }

</script>
<style  scoped lang="scss">
.draggable-navbar {
    z-index:1;
    /* 添加您的样式 */
    // transition: transform 0.1s;
}
</style>